<template>
  <el-dialog
    :visible.sync="dialog"
    :close-on-click-modal="false"
    :title="title"
    width="750px"
    :append-to-body="true"
    top="5px"
    @close="doClose"
  >
    <el-container>
      <div>
        <div class="field-divider">
          <el-divider content-position="left">
            <span style="color: #409EFF;">变量信息</span>
          </el-divider>
        </div>
        <div style="margin-top:25px;">
          <el-form ref="editForm" :model="entity" :rules="rules" label-width="auto" size="mini">
            <el-row>
              <el-col :span="24">
                <el-form-item size="mini" label="变量KEY:" :required="editDisabled" prop="variableKey">
                  <el-input v-model="entity.variableKey" size="mini" placeholder="请输入" :disabled="editDisabled" maxlength="128" show-word-limit style="width: 600px;" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item size="mini" label="变量名称:" :required="editDisabled" prop="variableName">
                  <el-input v-model="entity.variableName" size="mini" placeholder="请输入" :disabled="editDisabled" maxlength="128" show-word-limit style="width: 600px;" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item size="mini" label="备注:" prop="remark">
                  <el-input v-model="entity.remark" type="textarea" maxlength="512" show-word-limit rows="1" size="mini" placeholder="请输入" :disabled="editDisabled" style="width: 600px;" />
                </el-form-item>
              </el-col>
            </el-row>
            <div class="field-divider">
              <el-divider content-position="left">
                <span style="color: #409EFF;">变量属性</span>
              </el-divider>
            </div>
            <div style="margin-bottom:5px;with:600px;text-align:right;">
              <el-button type="primary" :disabled="editDisabled" size="mini" @click="toAddField()">新增</el-button>
            </div>
            <el-row>
              <el-col :span="24">
                <el-table
                  ref="dataList"
                  :data="dataList"
                  :row-class-name="tableRowClassName"
                  size="small"
                  border
                  :height="tableHeight"
                  :header-cell-style="{ height: '0px', padding: '0px' }"
                  :row-style="{height: '0px'}"
                  :cell-style="{padding: '0px'}"
                  style="width: 100%;"
                >
                  <el-table-column type="index" :index="tableIndex" label="序号" />
                  <el-table-column :show-overflow-tooltip="true" label="属性KEY" prop="fieldKey" />
                  <el-table-column :show-overflow-tooltip="true" label="属性名称" prop="fieldName" />
                  <el-table-column :show-overflow-tooltip="true" label="数据类型" prop="dataType">
                    <template slot-scope="scope">
                      {{ showNameByValue(scope.row.dataType, parent.dataTypes) }}
                    </template>
                  </el-table-column>
                  <el-table-column :show-overflow-tooltip="true" label="数据格式" prop="dataFormat" />
                  <el-table-column :show-overflow-tooltip="true" label="备注" prop="remark" />
                  <el-table-column v-if="!editDisabled" label="操作" prop="operation" align="center" fixed="right" width="80">
                    <template slot-scope="scope">
                      <div class="list-operation">
                        <el-link size="mini" type="warning" style="margin-left:0px;" @click="toModifyField(scope.row)">
                          <span style="font-size: 12px;">修改</span>
                        </el-link>
                        <el-link size="mini" type="danger" style="margin-left:0px;" @click="deleteField(scope.row)">
                          <span style="font-size: 12px;">删除</span>
                        </el-link>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item size="mini" prop="variableFields" />
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </el-container>
    <el-row v-if="!editDisabled" :gutter="20" style="margin-top:30px;">
      <el-col :span="24">
        <div style="text-align: right;">
          <el-button size="small" @click="doClose()">取消</el-button>
          <el-button type="primary" size="small" @click="doSave()">保存</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row v-else :gutter="20" style="margin-top:30px;">
      <el-col :span="13">
        <div style="text-align: right;">
          <div><el-button type="primary" size="small" @click="doClose()">关闭</el-button></div>
        </div>
      </el-col>
    </el-row>
    <fieldEdit ref="fieldEdit" :parent="currentObj" />
  </el-dialog>
</template>
<script>
import { Message } from 'element-ui'
import { parseToString } from '@/utils/datefromat'
import { showNameByValue } from '@/utils/selectUtil'
import { getSelector } from './js/variable'
import Rule from './js/variable-rules'
import Validate from './js/variable-validates'
import fieldEdit from './field-edit'
import { getEmptyVariable } from './js/variable'
import { addRuleVariable, updateRuleVariable } from '@/api/coi/configuration/rule-config/rule-variable'

export default {
  components: { fieldEdit },
  props: {
    parent: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialog: false,
      loading: false,
      currentObj: this,
      activeName: 'edit',
      title: '',
      rules: {},
      rule: new Rule(this),
      validate: new Validate(this),
      tableHeight: window.innerHeight * 0.45,
      variableFields: [],
      entity: this.getEmptyVariable(),
      params: {},
      query: {},
      time: 170,
      editDisabled: false
    }
  },
  computed: {
    dataList: function() {
      return this.entity.variableFields
    },
    showSaveButton: function() {
      return !this.entity.id
    },
    disabled: function() {
      return this.entity.id !== undefined && this.entity.dataStatus !== null
    }
  },
  created() {
    this.$nextTick(() => {
    })
  },
  mounted() {
    this.$nextTick(() => {
      this.rule.initRules()
    })
  },
  methods: {
    getSelector,
    showNameByValue,
    parseToString,
    getEmptyVariable,
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 0) {
        return 'bg-row'
      }
      return ''
    },
    tableIndex(index) {
      return index + 1
    },
    toAddField() {
      console.log('toAddField')
      var fieldEdit = this.$refs.fieldEdit
      fieldEdit.title = '新增属性'
      fieldEdit.entity.variableId = this.entity.id
      fieldEdit.dialog = true
    },
    toModifyField(field) {
      console.log('toModifyField')
      var fieldEdit = this.$refs.fieldEdit
      var json = JSON.stringify(field)
      var copyEntity = JSON.parse(json)
      fieldEdit.title = '修改属性'
      fieldEdit.entity = copyEntity
      fieldEdit.dialog = true
    },
    deleteField(field) {
      console.log('deleteField')
      var self = this
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var index = -1
        for (var i = 0; i < self.entity.variableFields.length; i++) {
          if (self.entity.variableFields[i].uuid === field.uuid) {
            index = i
            break
          }
        }
        if (index !== -1) {
          self.entity.variableFields.splice(index, 1)
        }
      })
    },
    // 关闭
    doClose() {
      this.dialog = false
      this.entity = this.getEmptyVariable()
      this.$refs.editForm.clearValidate()
    },
    // 保存
    doSave() {
      console.log('entity:' + JSON.stringify(this.entity))
      var _this = this
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm('确认保存？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            _this.loading = true
            if (!_this.entity.id) { // 新增
              addRuleVariable(_this.parent.baseUrl, _this.entity).then(res => {
                Message({
                  message: res.result,
                  type: 'success',
                  duration: 2 * 1000
                })
                _this.doClose()
                _this.parent.toQuery()
                _this.loading = false
              }, error => {
                console.log(error)
                _this.loading = false
              })
            } else { // 修改
              updateRuleVariable(_this.parent.baseUrl, _this.entity).then(res => {
                Message({
                  message: res.result,
                  type: 'success',
                  duration: 2 * 1000
                })
                _this.doClose()
                _this.parent.toQuery()
                _this.loading = false
              }, (error) => {
                console.log(error)
                _this.loading = false
              })
            }
          })
        } else {
          Message({
            message: '校验失败',
            type: 'warning',
            duration: 2 * 1000
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.field-divider >>> .el-divider--horizontal {
  margin: 5px 0px;
}
</style>
